package cn.lq.app.controller;

import cn.lq.app.dto.ApkVo;
import cn.lq.app.dto.LookPage;
import cn.lq.app.dto.ShenHeApp;
import cn.lq.app.entity.AppInfo;
import cn.lq.app.entity.AppVersion;
import cn.lq.app.entity.DevUser;
import cn.lq.app.service.AppInfoService;
import cn.lq.app.utils.SesstionUtils;
import cn.lq.app.vo.ResultVo;
import cn.lq.app.vo.TreesVo;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;

import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;


import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@RestController
@RequestMapping("/appInfo")
@Api(tags = "软件信息操作接口")
public class AppinfoController {

    @Resource
    AppInfoService appInfoService;


    @PostMapping("/page")
    public ResultVo paget(@RequestBody LookPage lookPage, HttpServletRequest request, @RequestParam(defaultValue = "1") Integer num) {
        AppInfo appInfo = new AppInfo();
        BeanUtils.copyProperties(lookPage, appInfo);
        String token = request.getHeader("token");
        String[] split = token.split("-");
        if (split[3].equals("1")) {
            appInfo.setStatus(1L);
        } else {
            appInfo.setDevid(Long.valueOf(split[2]));
        }
        PageInfo<AppInfo> page = appInfoService.getPage(appInfo, num);
        return ResultVo.success("", page);
    }

    @GetMapping("/tree")
    public ResultVo tree(HttpServletRequest request) {
        TreesVo list = appInfoService.getTrees(request);
        return ResultVo.success("", list);
    }

    @RequestMapping("/addAndUp")
    public ResultVo addAndUp(AppInfo appInfo, MultipartFile file, HttpServletRequest request) {
        String token = request.getHeader("token");
        if (file != null && (!file.isEmpty())) {
            String filename = file.getOriginalFilename();
            String path = request.getServletContext().getRealPath("/img");
            File file1 = new File(path);
            if (!file1.exists()) {
                file1.mkdirs();
            }
            String substring = filename.substring(filename.lastIndexOf("."));
            if (file.getSize() > 1024 * 1000) {
                throw new RuntimeException("文件太大");
            } else if (
                    substring.equalsIgnoreCase(".jpg") ||
                            substring.equalsIgnoreCase(".gif") ||
                            substring.equalsIgnoreCase(".jpeg") ||
                            substring.equalsIgnoreCase(".png")) {
                try {
                    String replace = UUID.randomUUID().toString().replace("-", "") + substring;
                    File file2 = new File(path + "/" + replace);
                    file.transferTo(file2);
                    appInfo.setLogopicpath("img/" + replace);
                } catch (IOException e) {
                    e.printStackTrace();
                    throw new RuntimeException("上传失败");
                }

            } else {
                throw new RuntimeException("文件格式不正确");
            }
        }

        DevUser devUser = (DevUser) SesstionUtils.get(token);
        if (appInfo.getId() == null) {
            appInfo.setCreatedby(devUser.getId());
            appInfo.setCreationdate(new Date());
            appInfo.setStatus(1L);
            appInfo.setDevid(devUser.getId());
        } else {
            appInfo.setModifyby(devUser.getId());
            appInfo.setModifydate(new Date());
            appInfo.setStatus(1L);
        }
        appInfoService.addAndUp(appInfo);
        return ResultVo.success("操作成功", "");
    }

    @PostMapping("/yanApkName")
    public ResultVo yanApkName(@RequestBody ApkVo apkVo) {
        AppInfo appInfo = new AppInfo();
        BeanUtils.copyProperties(apkVo, appInfo);
        boolean f = appInfoService.getApkName(appInfo);
        if (!f) {
            return ResultVo.error("apk名称已被占用");
        } else {
            return ResultVo.success("", "");
        }
    }

    @GetMapping("getOne/{id}")
    public ResultVo getOne(@PathVariable Integer id) {
        return ResultVo.success("", appInfoService.getOne(id));
    }


    @DeleteMapping("/del/{id}")
    public ResultVo del(@PathVariable Long id, HttpServletRequest request) {
        try {
            appInfoService.del(id, request);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultVo.error("删除失败");
        }
        return ResultVo.success("删除成功", "");
    }

    @PostMapping("/upStatus")
    public ResultVo upStatus(@RequestBody AppInfo appInfo) {
        if (appInfo.getStatus() == 4L) {
            appInfo.setStatus(5L);
        } else if (appInfo.getStatus() == 2L || appInfo.getStatus() == 5L) {
            appInfo.setStatus(4L);
        }
        try {
            appInfoService.addAndUp(appInfo);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultVo.success("修改失败", "");
        }
        return ResultVo.success("修改成功", "");
    }

    @GetMapping("/getVerList/{id}")
    public ResultVo getVerList(@PathVariable Long id) {
        List<AppVersion> list = appInfoService.getVerList(id);
        return ResultVo.success("", list);
    }

    @RequestMapping("/addVerAndUpVer")
    public ResultVo addVerAndUpVer(AppVersion appVersion, MultipartFile apkfile, HttpServletRequest request) {
        String token = request.getHeader("token");
        if (apkfile != null && (!apkfile.isEmpty())) {
            String filename = apkfile.getOriginalFilename();
            String path = request.getServletContext().getRealPath("/apk");
            File file1 = new File(path);
            if (!file1.exists()) {
                file1.mkdirs();
            }
            String substring = filename.substring(filename.lastIndexOf("."));
            if (apkfile.getSize() > 1024 * 1000) {
                return ResultVo.error("文件太大");
            } else if (
                    substring.equalsIgnoreCase(".apk")) {
                try {
                    String replace = UUID.randomUUID().toString().replace("-", "") + substring;
                    File file2 = new File(path + "/" + replace);
                    apkfile.transferTo(file2);
                    appVersion.setDownloadlink("apk/" + replace);
                } catch (IOException e) {
                    e.printStackTrace();
                    return ResultVo.error("上传失败");
                }

            } else {
               return ResultVo.error("文件格式不正确");
            }
        }

        DevUser devUser = (DevUser) SesstionUtils.get(token);
        if (appVersion.getId() == null) {
            appVersion.setCreatedby(devUser.getId());
            appVersion.setCreationdate(new Date());
            appVersion.setPublishstatus(3L);
            appInfoService.addVerOrUpVer(appVersion);
            AppInfo appInfo = new AppInfo();
            appInfo.setVersionid(appVersion.getId());
            appInfo.setId(appVersion.getAppid());
            appInfoService.addAndUp(appInfo);
        } else {
            appVersion.setModifyby(devUser.getId());
            appVersion.setModifydate(new Date());
        }

        return ResultVo.success("操作成功", "");
    }

    @RequestMapping("/shenHe")
    public ResultVo upAppStatus(@RequestBody ShenHeApp shenHeApp){
        AppInfo appInfo=new AppInfo();
        BeanUtils.copyProperties(shenHeApp,appInfo);
        try {
            appInfoService.addAndUp(appInfo);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultVo.error("修改失败");
        }
        return ResultVo.success("修改失败", "");
    }

}
